#!/bin/sh
{% set profile = cookiecutter.template_profile -%}
{% set agent_worktrees = cookiecutter.enable_agent_worktrees == "yes" or (cookiecutter.enable_agent_worktrees == "profile_default" and profile in ["agent_assisted", "github_sdlc", "software_factory"]) -%}
{% set drift_checks = cookiecutter.enable_quality_drift_checks == "yes" or (cookiecutter.enable_quality_drift_checks == "profile_default" and cookiecutter.template_profile == "software_factory") -%}
set -eu

# Use the project environment when available so hook checks can see dev tools.
PY_RUN="python3"
if command -v uv >/dev/null 2>&1; then
  PY_RUN="uv run --frozen python"
fi

# Block direct updates to main, but allow the initial branch creation push.
ZERO_SHA="0000000000000000000000000000000000000000"
while read local_ref _local_sha remote_ref remote_sha
do
  if [ "$remote_ref" = "refs/heads/main" ] && [ "$remote_sha" != "$ZERO_SHA" ]; then
    echo "error: pushing to main is blocked by agent worktree policy." >&2
    echo "       Open a pull request from your agent branch instead." >&2
    exit 1
  elif [ "$remote_ref" = "refs/heads/main" ]; then
    echo "notice: allowing initial push that creates main." >&2
  fi
done

{% if agent_worktrees -%}
# Agent worktree guard
$PY_RUN scripts/agent_worktree.py guard --quiet

{% endif -%}
# Run configured quality-control checks.
{% if agent_worktrees -%}
$PY_RUN scripts/ci/check_agent_instruction_drift.py
{% endif -%}
{% if drift_checks -%}
$PY_RUN scripts/ci/check_code_drift.py
{% endif -%}
$PY_RUN scripts/ci/check_version_bump.py
$PY_RUN scripts/ci/check_markdown_links.py || \
  echo "warning: broken markdown links detected — fix before merging" >&2
{% if drift_checks -%}
$PY_RUN scripts/ci/check_simplification_drift.py || \
  echo "warning: simplification drift findings (report-only during calibration — see docs/quality/CODE_DRIFT_CONTROLS.md)" >&2
$PY_RUN scripts/ci/check_test_value.py || \
  echo "warning: test value findings (report-only during calibration)" >&2
$PY_RUN scripts/ci/check_dead_code.py || \
  echo "warning: dead code findings (report-only during calibration)" >&2
{% endif -%}
